// ajax请求拦截器
define("ApiInterceptor", ['OauthCache', 'OauthApi', 'ajaxhook', "env"],
  function (oauthCache, oauthApi) {
    const NOT_TOKEN_PATHS = oauthApi.getURLPaths();
    ah.proxy({
      onRequest: (config, handler) => {
        //请求发起前进入
        if (!config.url.match(BASE_URL)) {
          handler.next(config);
          return;
        }
        let attchToken = false;
        let endIndex = config.url.indexOf("?");
        if (endIndex == -1) {
          attchToken = NOT_TOKEN_PATHS.indexOf(config.url.replace(BASE_URL, "")) == -1;
        } else {
          attchToken = NOT_TOKEN_PATHS.indexOf(config.url.substring(BASE_URL.length, endIndex)) == -1;
        }
        if (attchToken) {
          config.headers.Authorization = 'bearer ' + getToken();
        }
        delete config.headers.attch_token
        handler.next(config);
      },
      onError: (err, handler) => {
        //请求发生错误时进入，比如超时；注意，不包括http状态码错误，如404仍然会认为请求成功
        handler.next(err);
      },
      //请求成功后进入
      onResponse: (response, handler) => {
        if (response.config.url.match(BASE_URL) && response.response != null) {
          let resp = JSON.parse(response.response);
          if (resp.errcode != 0) {
            //将业务异常，走callback的异常回调
            response.status = 400;
          } else if (resp.errcode == CODE_INVALID_TOKEN) {
            //TODO 授权token无效，重新登录

          }
        }
        handler.next(response)
      }
    });

    function getToken() {
      let token = oauthCache.getAccessToken();
      if (token == null) {
        let refreshToken = oauthCache.getRefreshToken();
        oauthApi.refreshToken(false, refreshToken, {
          onSuccess: function (data) {
            oauthCache.saveOauth(data.data);
            token = data.data.accessToken;
          },
          onError: function (errcode, errmsg) {
            console.error("token 刷新失败:", errcode, errmsg)
          }
        })
      }
      return token;
    }
  });